var express = require('express');
var MajorSchema = require('../../../modules/major');
var router = express.Router();

//列表显示 搜索查询
  router.get('/list', function(req, res, next) {
    // 初始化参数
    let page = req.query.page ? parseInt(req.query.page) : 1;
    let limit = req.query.limit ? parseInt(req.query.limit) : 10;
  
    // 查询参数
    let searchData = {};
    req.query.campus ? searchData.campus = { $regex: req.query.campus } : '';
    req.query.college ? searchData.college = { $regex: req.query.college } : '';
    if (typeof page !== 'number' || typeof limit !== 'number') {
      res.json({code: 500, msg: 'querys is type error'});
      return res.end();
    }
  
    new Promise((resolve, reject)=>{
        MajorSchema.paginate(searchData, { page: page, limit: limit }, function(err, result) {
        if (!err) {
          resolve(result);
        }else {
          reject(err);
        }
      });
    }).then(response=>{
      res.json({
        code: 200,
        data: response.docs,
        count: response.total,
        pages: response.pages
      });
      return res.end();
    }).catch(error=>{
      res.json({code: 500, msg: error, query: req.query});
      return res.end();
    });
  });
  //删除
  router.post('/del', function (req, res, next) {
    if (!req.body.id) {
      res.json({code: 500, msg: '缺少参数id'});
      return res.end();
    }
    MajorSchema.findOne({_id: req.body.id}).exec((err, doc)=>{
      if (!err && doc) {
        MajorSchema.remove({_id: doc._id}, (err) => {
          if (!err) {
            res.json({code: 200, msg: '成功去除该专业！'});
            return res.json();
          } else {
            res.status(500);
            res.json({code: 10000, msg: '数据库异常，删除失败'});
            return res.end();
          }
        });
      } else {
        res.status(500);
        res.json({code: 10000, msg: '数据库异常，查询失败'});
        return res.end();
      }
    });
  });
  //新增
  router.post('/add', function(req, res, next) {
    let name = req.body.name;
    new Promise((resolve, reject)=>{
      var query  = MajorSchema.where({'name' : name});
      query.findOne(function (err, doc){
        if (!err && !doc) {
          resolve();
        }else {
          reject(err);
        }
      });
    }).then(()=>{
      let insertData = new MajorSchema({
        'campus': req.body.campus ? req.body.campus : '',
        'college': req.body.college ? req.body.college : '',
        'name': req.body.name ? req.body.name : '',
      }, false);
      insertData.save(function (err) {
        if (err) {
          res.json({code: 401, msg: '新增失败，请重试！'});
          return res.end();
        } else {
          res.json({code: 200, msg: '新增成功！' });
          return res.end();
        }
      });
    }).catch(()=>{
      res.json({code: 500, msg: '该专业信息已存在！'});
      return res.end();
    });
  });
  //编辑
  router.post('/upd', function(req, res, next){
    let data = req.body
    MajorSchema.findByIdAndUpdate({ _id: data._id }, {$set: {
      'campus': req.body.campus ? req.body.campus : '',
      'college': req.body.college ? req.body.college : '',
      'name': req.body.name ? req.body.name : '',
    }}, function (err, raw) {
      if (!err) {
        res.json({code: 200, msg: '更新成功'});
        return res.end();
      } else {
        res.json({code: 500, msg: '更新失败'});
        return res.end();
      }
    }); 
  });
  router.get('/allList', function (req, res, next) {
    let cond = {};
    req.query.college ? cond.college = { $regex: req.query.college} : '';

    MajorSchema.find(cond,{'name':1}).exec((err, doc)=>{
      if (!err && doc) {
        res.json({
          code: 200,
          data: doc,
        });
        return res.end();
      } else {
        res.status(500);
        res.json({code: 10000, msg: '数据库异常，查询失败'});
        return res.end();
      }
    })
  })
  module.exports = router;
  